{
    MyDesktop.storeTemplate = new Ext.data.Store({
                id       : 'storeTemplate',
                proxy    : new Ext.data.HttpProxy({
                            url    : '<?=BASE_URL?>/template/list-all',
                            method : 'POST'
                        }),
                reader   : new Ext.data.JsonReader({
                            root          : 'results',
                            totalProperty : 'total'
                        }, [{
                                name : 'template_id'
                            }, {
                                name : 'template_name'
                            }]),
                autoLoad : true
            });

    MyDesktop.cboTemplate = new Ext.form.ComboBox({
                name          : 'template_id',
                fieldLabel    : 'Template',
                width         : 170,
                height        : 24,
                bodyStyle     : 'padding:15px',
                store         : MyDesktop.storeTemplate,
                // id : 'template_id',
                valueField    : 'template_id',
                displayField  : 'template_name',
                hiddenName    : 'template_id',
                typeAhead     : true,
                mode          : 'local',
                triggerAction : 'all',
                emptyText     : '- Choose -',
                selectOnFocus : true,
                editable      : false
            });

    function parentPath(store, node) {
        parentNodes = store.getNodeParent(node);
        if (parentNodes) {
            return parentPath(store, parentNodes) + ' >> '
                    + node.get('admin_title');
        }
        return node.get('admin_title');
    };
    
    strStatus = new Ext.data.SimpleStore({
                fields : ['value', 'id'],
                data   : [['Disable', '0'], ['Enable', '1']]
            });

    cboStatus = new Ext.form.ComboBox({
                name          : 'status',
                fieldLabel    : '<?=$this->translate->_("Status")?>',
                width         : 170,
                height        : 24,
                bodyStyle     : 'padding:15px',
                store         : strStatus,
                valueField    : 'id',
                displayField  : 'value',
                hiddenName    : 'status',
                value         : 0,
                typeAhead     : true,
                mode          : 'local',
                triggerAction : 'all',
                emptyText     : '- <?=$this->translate->_("Select value...")?> -',
                selectOnFocus : true,
                editable      : false,
                allowBlank    : false
            });
    
    strShowInMainMenu = new Ext.data.SimpleStore({
                fields : ['value', 'id'],
                data   : [['Disable', '0'], ['Enable', '1']]
            });

    cboShowInMainMenu = new Ext.form.ComboBox({
                name          : 'main_menu',
                fieldLabel    : '<?=$this->translate->_("ShowInMainMenu")?>',
                width         : 170,
                height        : 24,
                bodyStyle     : 'padding:15px',
                store         : strShowInMainMenu,
                valueField    : 'id',
                displayField  : 'value',
                hiddenName    : 'main_menu',
                value         : 0,
                typeAhead     : true,
                mode          : 'local',
                triggerAction : 'all',
                emptyText     : '- <?=$this->translate->_("Select value...")?> -',
                selectOnFocus : true,
                editable      : false,
                allowBlank    : false
            });

    Ext.tree.ColumnNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
        focus          : Ext.emptyFn, // prevent odd scrolling behavior

        renderElements : function(n, a, targetNode, bulkRender) {
            this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';

            var t = n.getOwnerTree();
            var cols = t.columns;
            var bw = t.borderWidth;
            var c = cols[0];

            var buf = [
                '<li class="x-tree-node"><div ext:tree-node-id="',
                n.id,
                '" class="x-tree-node-el x-tree-node-leaf ',
                a.cls,
                '">',
                '<div class="x-tree-col" style="width:',
                c.width - bw,
                'px;">',
                '<span class="x-tree-node-indent">',
                this.indentMarkup,
                "</span>",
                '<img src="',
                this.emptyIcon,
                '" class="x-tree-ec-icon x-tree-elbow">',
                '<img src="',
                a.icon || this.emptyIcon,
                '" class="x-tree-node-icon',
                (a.icon ? " x-tree-node-inline-icon" : ""),
                (a.iconEditDel ? " " + a.iconEditDel : ""),
                '" unselectable="on">',
                '<a hidefocus="on" class="x-tree-node-anchor" href="',
                a.href ? a.href : "#",
                '" tabIndex="1" ',
                a.hrefTarget ? ' target="' + a.hrefTarget + '"' : "",
                '>',
                '<span unselectable="on">',
                n.text
                        || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),
                "</span></a>", "</div>"];
            for (var i = 1, len = cols.length; i < len; i++) {
                c = cols[i];

                buf
                        .push(
                                '<div class="x-tree-col ',
                                (c.cls ? c.cls : ''),
                                '" style="width:',
                                c.width - bw,
                                'px;">',
                                '<div class="x-tree-col-text">',
                                (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),
                                "</div>", "</div>");
            }
            buf.push('<div class="x-clear"></div></div>',
                    '<ul class="x-tree-node-ct" style="display:none;"></ul>',
                    "</li>");

            if (bulkRender !== true && n.nextSibling
                    && n.nextSibling.ui.getEl()) {
                this.wrap = Ext.DomHelper.insertHtml("beforeBegin",
                        n.nextSibling.ui.getEl(), buf.join(""));
            } else {
                this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode,
                        buf.join(""));
            }

            this.elNode = this.wrap.childNodes[0];
            this.ctNode = this.wrap.childNodes[1];
            var cs = this.elNode.firstChild.childNodes;
            this.indentNode = cs[0];
            this.ecNode = cs[1];
            this.iconNode = cs[2];
            this.anchor = cs[3];
            this.textNode = cs[3].firstChild;
        }
    });
    // End define
    Ext.tree.ColumnTree = Ext.extend(Ext.tree.TreePanel, {
        lines       : false,
        borderWidth : Ext.isBorderBox ? 0 : 2, // the combined left/right
        // border for each cell
        cls         : 'x-column-tree',
        expanded    : true,
        onRender    : function() {
            Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
            this.headers = this.body.createChild({
                        cls : 'x-tree-headers'
                    }, this.innerCt.dom);

            var cols = this.columns, c;
            var totalWidth = 0;

            for (var i = 0, len = cols.length; i < len; i++) {
                c = cols[i];
                totalWidth += c.width;
                this.headers.createChild({
                            cls   : 'x-tree-hd ' + (c.cls ? c.cls + '-hd' : ''),
                            cn    : {
                                cls  : 'x-tree-hd-text',
                                html : c.header
                            },
                            style : 'width:' + (c.width - this.borderWidth)
                                    + 'px;'
                        });
            }
            this.headers.createChild({
                        cls : 'x-clear'
                    });
            this.headers.setWidth(totalWidth);
            this.innerCt.setWidth(totalWidth);
        }
    });

    Ext.tree.ColumnTree = Ext.extend(Ext.tree.TreePanel, {
        lines       : false,
        borderWidth : Ext.isBorderBox ? 0 : 2, // the combined left/right
        // border for each cell
        cls         : 'x-column-tree',
        expanded    : true,
        onRender    : function() {
            Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
            this.headers = this.body.createChild({
                        cls : 'x-tree-headers'
                    }, this.innerCt.dom);

            var cols = this.columns, c;
            var totalWidth = 0;

            for (var i = 0, len = cols.length; i < len; i++) {
                c = cols[i];
                totalWidth += c.width;
                this.headers.createChild({
                            cls   : 'x-tree-hd ' + (c.cls ? c.cls + '-hd' : ''),
                            cn    : {
                                cls  : 'x-tree-hd-text',
                                html : c.header
                            },
                            style : 'width:' + (c.width - this.borderWidth)
                                    + 'px;'
                        });
            }
            this.headers.createChild({
                        cls : 'x-clear'
                    });
            this.headers.setWidth(totalWidth);
            this.innerCt.setWidth(totalWidth);
        }
    });

    function expandAllNodes(store) {
        store.data.each(function(record) {
                    if (!store.isLeafNode(record) && store.isLoadedNode(record)) {
                        store.expandNode(record);
                    }
                });
    }

    /** ******************************************************************************************************************** */

    // create the data store
    var recordPage = Ext.data.Record.create([{
            name : 'admin_title'
        }, {
            name : 'action'
        }, {
            name : '_id',
            type : 'int'
        }, {
            name : 'path',
            type : 'string'
        }, {
            name : '_level',
            type : 'int'
        }, {
            name : 'parent',
            type : 'int'
        }, {
            name : 'status',
            type : 'int'
        }, {
            name : '_lft',
            type : 'int'
        }, {
            name : '_rgt',
            type : 'int'
        }, {
            name : 'template_id',
            type : 'int'
        }, {
            name : 'main_menu',
            type : 'int'
        }, {
            name : '_is_leaf',
            type : 'bool'
        }]);

    MyDesktop.CategoryManagement = Ext.extend(Ext.app.Module, {
        createWindow : function() {
            var desktop = app.getDesktop();
            var win = desktop.getWindow('listCategory');
            if (!win) {
                win = desktop.createWindow({
                    id          : 'listCategory',
                    title       : "<?=$this->translate->_('Category Management')?>",
                    width       : <?=$this->winWidth?>,
                    height      : <?=$this->winHeight?>,
                    iconCls     : 'icon-grid',
                    layout      : 'border',
                    maximizable : false,

                    tbar        : [{
                            id      : 'refresh',
                            text    : "<?=$this->translate->_('Refresh')?>",
                            icon    : '<?=ICONS_PATH?>/refresh16x16.png',
                            cls     : "x-btn-text-icon",
                            handler : function() {
                                // activeNode =
                                // MyDesktop.GridCategory.getStore().active_node;

                                MyDesktop.GridCategory.getStore().reload();
                                // alert(activeNode);
                                // MyDesktop.GridCategory.getStore().activeNode(activeNode);
                                // MyDesktop.GridCategory.getStore().reload();
                                // MyDesktop.GridCategory.reload();
                            }
                        }, {
                            id      : 'expand-all-node',
                            text    : "<?=$this->translate->_('Expand All')?>",
                            icon    : '<?=ICONS_PATH?>/refresh16x16.png',
                            handler : function() {
                                MyDesktop.GridCategory.expandAll();
                            }
                        }],

                    items       : [MyDesktop.GridCategory,
                        MyDesktop.CategoryManagement.tabRight
                    /* MyDesktop.CategoryManagement.formAdd */],

                    listeners   : {
                        close : function() {
                        }
                    }

                });
            }
            <?php
            if ($this->maximizeWin) {
            echo "win.maximize();";
            }
            ?>
            win.show();

        }
    });
    MyDesktop.CategoryManagement.deleteCategory = function() {
        // submit code here
        var categoryName = '';
        var categoryId = 0;
        try {
            categoryName = MyDesktop.GridCategory.getStore().active_node
                    .get('admin_title');
            categoryId = MyDesktop.GridCategory.getStore().active_node
                    .get('_id');
        } catch (e) {
        }
        // alert(storePage.getNodePrevSibling(MyDesktop.GridCategory.getStore().active_node));
        if (0 != categoryId) {
            Ext.Msg.confirm("<?=$this->translate->_('Confirm box')?>",
                    "<?=$this->translate->_('Are you sure to <b>delete</b> category <b>')?>"
                            + categoryName + "</b>", function(btn, text) {
                        if (btn == 'yes') {
                            Ext.Ajax.request({
                                url     : '<?=BASE_URL?>/<?=$this->currentController?>/delete/id/'
                                        + categoryId,
                                success : function(r) {
                                    var form = MyDesktop.CategoryManagement.formAdd;
                                    MyDesktop.GridCategory.getStore().currentNode = 0;

                                    MyDesktop.CategoryManagement.dataStore
                                            .reload();
                                    Ext.Msg
                                            .alert(
                                                    '<?=$this->translate->_("Status")?>',
                                                    '<?=$this->translate->_("Delete successfull!")?>');
                                    form.getForm().reset();
                                },
                                failure : function(r) {
                                    Ext.Msg
                                            .alert(
                                                    '<?=$this->translate->_("Status")?>',
                                                    '<?=$this->translate->_("Request Fail! Please check your connection")?>');
                                }
                            });

                        }
                    });
        } else {
            Ext.Msg.alert("<?=$this->translate->_('Alert')?>",
                    "<?=$this->translate->_('Please choose category!')?>");
        }

    }
    MyDesktop.CategoryManagement.editCategory = function() {
        var categoryId = 0;
        try {
            categoryId = MyDesktop.GridCategory.getStore().active_node
                    .get('_id');
        } catch (e) {
        }
        if (categoryId != 0) {
            var store = MyDesktop.GridCategory.getStore();
            MyDesktop.CategoryManagement.formAdd.getForm()
                    .loadRecord(store.active_node);
            Ext.getCmp('fieldset-edit-cat').setTitle(parentPath(store,
                    store.active_node));
        }
    }

    MyDesktop.CategoryManagement.dataStore = new Ext.ux.maximgb.treegrid.NestedSetStore(
            {
                autoLoad   : true,
                id         : 'cms-store-page',
                url        : '<?=BASE_URL?>/category/data',
                reader     : new Ext.data.JsonReader({
                            id              : '_id',
                            root            : 'data',
                            name            : 'admin_title',
                            totalProperty   : 'total',
                            successProperty : 'success'
                        }, recordPage),
                listeners  : {
                    'load'           : function(thisStore, records, options) {
                        MyDesktop.GridCategory.getSelectionModel()
                                .clearSelections();
                        collapsed = false;
                        // MyDesktop.GridCategory.expandAll();
                        // alert(MyDesktop.GridCategory.getStore().currentNode);
                        if ('undefined' != ''
                                + MyDesktop.GridCategory.getStore().currentNode) {
                            thisStore.activeNode(MyDesktop.GridCategory
                                    .getStore().currentNode);
                            thisStore.setActiveNode(MyDesktop.GridCategory
                                    .getStore().currentNode);
                        }
                    },
                    activenodechange : function(store, old_rc, new_rc) {
                        // MyDesktop.GridCategory.getStore().currentNode =
                        // new_rc;
                        // MyDesktop.CategoryManagement.formAdd.expand(true);
                        // MyDesktop.CategoryManagement.formAdd.getForm()
                        // .loadRecord(new_rc);
                        // MyDesktop.CategoryManagement.formAdd.setTitle(MyDesktop.GridCategory.getView().getBreadcrumbsEl().dom.innerHTML);
                        // console.log(MyDesktop.GridCategory.getView().getBreadcrumbsEl().dom.innerHTML);

                        // alert(MyDesktop.GridCategory.getView().getBreadcrumbsEl().dom.innerHTML);
                        // console.log(storePage.getNodeParent(rec));
                        // alert(rec.get('_id'));
                    }
                },

                activeNode : function(node) {
                    try {
                        var parentNode = MyDesktop.GridCategory.getStore()
                                .getNodeParent(node);
                        if (parentNode)
                            this.activeNode(parentNode);
                    } catch (ex) {
                    }
                    this.expandNode(node);
                }
            });

    // create the Grid
    MyDesktop.GridCategory = new Ext.ux.maximgb.treegrid.GridPanel({
        store            : MyDesktop.CategoryManagement.dataStore,
        id               : 'category-grid',
        currentNode      : 0,
        master_column_id : 'admin_title',
        region           : 'center',
        columns          : [{
                id        : 'admin_title',
                header    : "admin_title",
                width     : 220,
                sortable  : true,
                dataIndex : 'admin_title'
            }, {
                id        : 'path',
                header    : "path",
                width     : 220,
                sortable  : true,
                dataIndex : 'path',
                hidden    : true
            }, {
                id        : 'action',
                header    : "action",
                width     : 200,
                sortable  : true,
                dataIndex : 'action'
            }],
        enableDragDrop   : true,
        enableDD         : true,
        containerScroll  : true,

        stripeRows       : true,
        autoExpandColumn : 'admin_title',
        root_title       : "<?=$this->translate->_('Root')?>",

        selModel         : new Ext.grid.RowSelectionModel({
                    singleSelect : true,
                    listeners    : {
                        rowselect : function(sm, row, rec) {
                            // MyDesktop.CategoryManagement.formAdd.setTitle();
                            // Ext.getCmp('parent_path').setValue(parentPath(store,
                            // rec));
                            // Ext.getCmp('fieldset-edit-cat').setTitle(parentPath(store,
                            // rec));

                            // alert(MyDesktop.GridCategory.getView().getBreadcrumbsEl().dom.innerHTML);
                            // console.log(storePage.getNodeParent(rec));
                            // alert(rec.get('_id'));
                        }
                    }
                }),
        listeners        : {
            cellclick : function(grid, rowIndex, columnIndex, e) {
                var store = grid.getStore();
                var rec = store.getAt(rowIndex);
                var store = MyDesktop.GridCategory.getStore();
                store.currentNode = rec;
                MyDesktop.CategoryManagement.formAdd.expand(true);
                var activeType = MyDesktop.CategoryManagement.tabRight.activeType;

                if (columnIndex == 0) {
                    if ('EDIT_CAT' == activeType) {
                        // Change parent ID of form Add/Edit
                        // MyDesktop.CategoryManagement.formAdd.getForm()
                        // .loadRecord(rec);
                        // alert(rec.get('id'));
                        var form = MyDesktop.CategoryManagement.formAdd
                                .getForm();
                        var currentCategory = form.findField('_id').getValue();
                        // alert(currentCategory + '-' + rec.get('_id'));
                        var parentCategory = form.findField('parent');
                        var parentNode = form.findField('path');
                        if (rec.get('_id') != currentCategory) {
                            parentCategory.setValue(rec.get('_id'));
                            parentNode.setValue(rec.get('path') + ' >> '
                                    + rec.get('admin_title'));
                        }
                    }
                }
            }
        },

        expandAll        : function() {
            var store = MyDesktop.GridCategory.getStore();
            store.data.each(function(record) {
                        if (!store.isLeafNode(record)
                                && store.isLoadedNode(record)) {
                            store.expandNode(record);
                        }
                    });
            // initializeExpnadCollapseToggleButtons();
        }
    });

    MyDesktop.CategoryManagement.tabRight = new Ext.TabPanel({
                id          : 'CategoryManagementTabRight',
                region      : "east",
                width       : 730,
                collapsible : true,
                split       : true,
                title       : "Manage Category/Items",
                activeTab   : 0,
                activeType  : ''
            });
    MyDesktop.CategoryManagement.formAdd = new Ext.FormPanel({
        id          : 'CategoryFormPanel',
        url         : '<?=BASE_URL?>/<?=$this->currentController?>/save',
        defaultType : 'textfield',
        autoScroll  : true,
        frame       : true,
        title       : '<?=$this->translate("Add/Edit Category")?>',
        listeners   : {
            activate : function(tab) {
                MyDesktop.CategoryManagement.tabRight.activeType = 'EDIT_CAT';
                // alert('Active');
            }
        },
        items       : [{
            xtype       : 'fieldset',
            id          : 'fieldset-edit-cat',
            title       : 'Field Set',
            autoHeight  : true,
            layout      : 'form',
            defaultType : 'textfield',
            items       : [{
                    fieldLabel : 'category_id',
                    name       : '_id',
                    id         : '_id',
                    style      : 'width:98%',
                    readOnly   : true
                }, {
                    fieldLabel : "<?=$this->translate->_('Title')?>",
                    name       : 'admin_title',
                    id         : 'admin_title',
                    style      : 'width:98%'
                }, {
                    fieldLabel : 'parent',
                    name       : 'parent',
                    id         : 'parent',
                    style      : 'width:98%',
                    readOnly   : true
                }, {
                    fieldLabel : 'parent path',
                    name       : 'path',
                    id         : 'path',
                    style      : 'width:98%',
                    readOnly   : true
                }, MyDesktop.cboTemplate, cboShowInMainMenu, cboStatus, {
                    xtype : 'label',
                    html  : "<?=$this->translate->_('<span style=\'padding-top:10px\'><i>Please choose left category to change parent</i></span>')?>"
                }]
        }],
        tbar        : [{
            id      : "submitFormEditCategory",
            text    : '<?=$this->translate->_("Save")?>',
            icon    : '<?=ICONS_PATH?>/save.gif',
            tooltip : '<?=$this->translate->_("Save to database")?>',
            handler : function() { // submit code here
                var form = MyDesktop.CategoryManagement.formAdd.form;
                form.submit({
                    waitMsg : '<?=$this->translate->_("Please wait")?>',
                    reset   : false,
                    success : function(f, a) {
                        // form.toBack();
                        var message = "<?=$this->translate->_('Can\'t save to DB!')?>";
                        try {
                            message = a.result.message;
                        } catch (ex) {
                        }
                        MyDesktop.CategoryManagement.dataStore.reload();
                        Ext.Msg.alert('<?=$this->translate->_("Status")?>',
                                message);
                    },
                    failure : function(f, a) {
                        // form.toBack();
                        var message = "<?=$this->translate->_('Your form is not valid!')?>";
                        try {
                            message = a.result.message;
                        } catch (ex) {
                        }
                        Ext.Msg.alert('<?=$this->translate->_("Status")?>',
                                message);
                    }
                });
            }
        }, {
            text    : '<?=$this->translate->_("Form Add")?>',
            icon    : '<?=ICONS_PATH?>/refresh16x16.png',
            cls     : "x-btn-text-icon",
            handler : function() {
                var form = MyDesktop.CategoryManagement.formAdd;

                form.getForm().reset();
            }

        }, {
            id      : 'Delete',
            text    : "<?=$this->translate->_('Delete')?>",
            icon    : '<?=ICONS_PATH?>/delete16x16.png',
            cls     : "x-btn-text-icon",
            handler : function() { // submit code here
                var form = MyDesktop.CategoryManagement.formAdd;

                var id = form.findById('<?=$this->pk?>').getValue();

                Ext.Ajax.request({
                    url     : '<?=BASE_URL?>/<?=$this->currentController?>/delete/id/'
                            + id,
                    success : function(r) {
                        MyDesktop.CategoryManagement.dataStore.reload();
                        Ext.Msg
                                .alert('<?=$this->translate->_("Status")?>',
                                        '<?=$this->translate->_("Delete successfull!")?>');
                        form.getForm().reset();
                    },
                    failure : function(r) {
                        Ext.Msg
                                .alert('<?=$this->translate->_("Status")?>',
                                        '<?=$this->translate->_("Request Fail! Please check your connection")?>');
                    }
                });
            }
        }]
    });

    // Ext.getCmp("ddddd").expand(true);
    // MyDesktop.ItemsManagement.findById('ddddd').expand();//setActiveItem(1);

    MyDesktop.CategoryManagement.tabRight
            .add(MyDesktop.CategoryManagement.formAdd);
    // MyDesktop.CategoryManagement.tabRight.setActiveTab(0);
    // MyDesktop.ItemsManagement.activeItem = 1;
    // Ext.getCmp("qqq").expand(true);

    var CategoryManagement = new MyDesktop.CategoryManagement();
    CategoryManagement.createWindow();

}
